//
//  AnjiMainViewController_Second.m
//  OASystem
//
//  Created by zhoupengfei on 16/3/26.
//  Copyright © 2016年 zpf. All rights reserved.
//
#import "ViewController3.h"
#import "dengjiTableViewController.h"
#import "AnjiMainViewController_Second.h"
#import "MainViewCell.h"
#import "OADueInViewController.h"
#import "OASMSViewController.h"
#import "OAUpComingWorkController.h"
#import "OAToDoWorkViewController.h"
#import "OANoteViewController.h"
#import "OANewInViewController.h"
#import "OANewSendViewController.h"
#import "OAInBoxViewController.h"
#import "OASendMessageViewController.h"
#import "OAHomeEmailViewController.h"
#import "OAAddressViewController.h"
#import "HttpTools.h"
#import "BaseModel.h"
#import "OALoginViewController.h"
#import "AuthHelper.h"

@interface HomeModel : BaseModel

@property(nonatomic,copy)NSString *  exchange;
@property(nonatomic,copy)NSString *  ksmail;
@property(nonatomic,copy)NSString *  mail;
@property(nonatomic,copy)NSString *  offiece;
@property(nonatomic,copy)NSString *  whetherExchange;
@property(nonatomic,copy)NSString *  whetherSms;
@property(nonatomic,copy)NSString * read;
@end

@implementation HomeModel

@end

@interface AnjiMainViewController_Second ()<UICollectionViewDelegateFlowLayout,SangforSDKDelegate>
@property(nonatomic,strong)NSMutableArray * contentArray;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *followLayout;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property(nonatomic,strong)HomeModel * homeModel;
@property(nonatomic,strong)NSMutableArray * originalData;
@property (nonatomic, strong) AuthHelper *helper;


@end

@implementation AnjiMainViewController_Second

short port = 443;                        //vpn设备端口号，一般为443
NSString *vpnIp1 =    @"61.175.232.5";  //vpn设备IP地址
NSString *userName1 = @"app";             //用户名认证的用户名
NSString *password1 = @"appapp";                //用户名认证的密码

NSString *certName1 = @"";     //导入证书名字，如果服务端没有设置证书认证可以不设置
NSString *certPwd1 =  @"";

static NSString * const reuseIdentifier = @"CellIdentifier";

-(NSMutableArray*)contentArray{
    if (_contentArray == nil) {
        _contentArray = [NSMutableArray array];
    }
    return _contentArray;
}

-(void)viewWillAppear:(BOOL)animated{
    
//    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"autoLogin"] isEqualToString:@"Y"]||[[[NSUserDefaults standardUserDefaults]objectForKey:@"shoushi"] isEqualToString:@"Y"]) {
        
        self.helper = [[AuthHelper alloc] initWithHostAndPort:vpnIp1 port:443 delegate:self];
        [self.helper setAuthParam:@AUTO_LOGIN_OFF_KEY param:@"true"];
        
//        [self updateApp];

    }
    
    NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray *  array = @[@{@"userId":userId}];;
    [HttpTools requestWithURL:KExchmain arrays:array method:KHomePqwoiunu success:^(id JSON) {
        NSArray *tempArray  = JSON[@"data"];
        NSDictionary * dict = [tempArray firstObject];
        self.homeModel = [[HomeModel alloc] initWitDictionary:dict];
        [self setupSubView];
    } failure:^(NSError *error) {
        
    }];
    
    
    
  
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSString * filePath =  [[NSBundle mainBundle] pathForResource:@"mainList" ofType:@"plist"];
    self.originalData = [NSMutableArray arrayWithContentsOfFile:filePath];
    [self.contentArray addObjectsFromArray:self.originalData];
    
    self.followLayout.sectionInset = UIEdgeInsetsMake(15, 8, 8, 8);
    self.followLayout.itemSize = CGSizeMake(([UIScreen mainScreen].bounds.size.width - 50 )/ 4 , ([UIScreen mainScreen].bounds.size.width - 50 )/ 4);
    self.followLayout.minimumLineSpacing = 40;

    [self updateApp];
    //定时器
     dispatch_async(dispatch_get_global_queue(0, 0), ^{
        _timer = [NSTimer scheduledTimerWithTimeInterval:300 target:self selector:@selector(makeview) userInfo:nil repeats:YES];
        // 开启当前线程
        [[NSRunLoop currentRunLoop] run];
    });

}

//app更新提示
- (void)updateApp{
    
    //获取app版本号
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *appVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    
    NSArray *array = @[@{@"veseion":appVersion}];
    
    [HttpTools requestWithURL:KExchmain arrays:array method:KUpdateDownMethod success:^(id JSON) {
        
        NSArray *array = JSON[@"data"];
        
        NSDictionary *dict = [array firstObject];
        
        NSString *url = dict[@"downlink"];
        NSString *index = dict[@"result"];
        
        if ([index isEqualToString:@"1"]) {
            
// 提示更新
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"更新" message:@"程序已经更新，请卸载完以前的版本，再重新下载" preferredStyle:UIAlertControllerStyleAlert];

            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel  handler:^(UIAlertAction * _Nonnull action) {
                
                  [_helper logoutVpn];

    OALoginViewController * loginVC =  [self.storyboard instantiateViewControllerWithIdentifier:@"LoginVC"];
             loginVC.type = @"1";

    self.view.window.rootViewController = loginVC;
                
            }];

            UIAlertAction *action = [UIAlertAction actionWithTitle:@"更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
               
                if (url.length != 0) {
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url]];

                }
                
            }];
            
            [alert addAction:cancelAction];
            [alert addAction:action];
            
            [self presentViewController:alert animated:YES completion:nil];
            
            
            
            
        }
        
    
    } failure:^(NSError *error) {
  
    
    
    }];
    
    
}

- (void)dealloc{

    [self dismissViewControllerAnimated:YES completion:nil];

}



#pragma Mark VPNDelegate
- (void) onCallBack:(const VPN_RESULT_NO)vpnErrno authType:(const int)authType
{
    switch (vpnErrno)
    {
        case RESULT_VPN_INIT_FAIL:
            NSLog(@"Vpn Init failed!");
            break;
            
        case RESULT_VPN_AUTH_FAIL:
            [self.helper clearAuthParam:@SET_RND_CODE_STR];
            NSLog(@"Vpn auth failed!");
            break;
            
        case RESULT_VPN_INIT_SUCCESS:
            NSLog(@"Vpn init success!");
            //设置认证参数 用户名和密码以数值map的形式传入
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_NAME param:userName1];
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_PASSWORD param:password1];
            //开始用户名密码认证
            [self.helper loginVpn:SSL_AUTH_TYPE_PASSWORD];
            break;
        case RESULT_VPN_AUTH_SUCCESS:
            [self startOtherAuth:authType];
            break;
        case RESULT_VPN_AUTH_LOGOUT:
            NSLog(@"Vpn logout success!");
            break;
        case RESULT_VPN_OTHER:
            if (VPN_OTHER_RELOGIN_FAIL == (VPN_RESULT_OTHER_NO)authType) {
                NSLog(@"Vpn relogin failed, maybe network error");
            }
            break;
            
        case RESULT_VPN_NONE:
            break;
            
        default:
            break;
    }
}

- (void) startOtherAuth:(const int)authType
{
    NSArray *paths = nil;
    switch (authType)
    {
            //            证书认证
        case SSL_AUTH_TYPE_CERTIFICATE:
            paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                        NSUserDomainMask, YES);
            
            if (nil != paths && [paths count] > 0)
            {
                NSString *dirPaths = [paths objectAtIndex:0];
                NSString *authPaths = [dirPaths stringByAppendingPathComponent:certName1];
                NSLog(@"PATH = %@",authPaths);
                //P12证书路径
                [self.helper setAuthParam:@CERT_P12_FILE_NAME param:authPaths];
                //证书的密码
                [self.helper setAuthParam:@CERT_PASSWORD param:certPwd1];
            }
            NSLog(@"Start Cert Auth!!!");
            break;
            
            /** 用户名密码认证 */
        case SSL_AUTH_TYPE_PASSWORD:
            NSLog(@"Start Password Name Auth!!!");
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_NAME param:userName1];
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_PASSWORD param:password1];
            
            break;
            /** 无认证 */
        case SSL_AUTH_TYPE_NONE:
            NSLog(@"Auth success!!!");
            [self makeview];
            return;
        default:
            NSLog(@"Other failed!!!");
            return;
    }
    [self.helper loginVpn:authType];
}

-(void)setupSubView{
    if ([self.homeModel.whetherExchange integerValue] == 0) {
        for (NSDictionary * dict in self.contentArray) {
            if ([dict[@"title"] isEqualToString:@"待收文件"] || [dict[@"title"] isEqualToString:@"已收文件"] || [dict[@"title"] isEqualToString:@"已发文件"]|| [dict[@"title"] isEqualToString:@"登记簿"]) {
                [self.originalData removeObject:dict];
            }
            
        }
    }
    
    if([self.homeModel.whetherSms integerValue] == 0) {
        for (NSDictionary * dict in self.contentArray) {
            if ([dict[@"title"] isEqualToString:@"短信平台"]) {
                [self.originalData removeObject:dict];
            }
        }
    }
    
    self.contentArray = [self.originalData mutableCopy];
    [self.collectionView reloadData];
}

- (void)makeview{

 NSString * userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userId"];
    NSArray *  array = @[@{@"userId":userId}];;
    [HttpTools requestWithURL:KExchmain arrays:array method:KHomePqwoiunu success:^(id JSON) {
        NSArray *tempArray  = JSON[@"data"];
        NSDictionary * dict = [tempArray firstObject];
        self.homeModel = [[HomeModel alloc] initWitDictionary:dict];
        [self setupSubView];
    } failure:^(NSError *error) {
        
    }];
}
#pragma mark <UICollectionViewDataSource>

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.contentArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    MainViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    //cell.backgroundColor = [UIColor redColor];
    NSDictionary * dict = self.contentArray[indexPath.item];
    cell.dict = dict;
    if ([dict[@"title"]isEqualToString:@"待收文件"]) {
        [cell.btnCount setTitle:self.homeModel.exchange forState:UIControlStateNormal];
        if ([self.homeModel.exchange integerValue] !=0) {
            cell.btnCount.hidden = NO;
        }else{
            cell.btnCount.hidden = YES;
        }
    }
    else if ([dict[@"title"] isEqualToString:@"待办文件"]) {
        [cell.btnCount setTitle:self.homeModel.offiece forState:UIControlStateNormal];
        if ([self.homeModel.offiece integerValue] !=0) {
            cell.btnCount.hidden = NO;
        }else{
            cell.btnCount.hidden = YES;
        }
        
    }
    
    else if ([dict[@"title"] isEqualToString:@"待阅文件"]) {
        [cell.btnCount setTitle:self.homeModel.read forState:UIControlStateNormal];
        if ([self.homeModel.read integerValue] !=0) {
            cell.btnCount.hidden = NO;
        }else{
            cell.btnCount.hidden = YES;
        }
    }else{
        cell.btnCount.hidden = YES;
    }
    [cell layoutIfNeeded];
    return cell;
}


#pragma mark <UICollectionViewDelegate>

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
   
    [self setupWithIndexPath:indexPath];
    
}

-(void)setupWithIndexPath:(NSIndexPath*)indexPath{
    NSDictionary * dict =  self.contentArray[indexPath.item];
     OADueInViewController * dueInVC = (OADueInViewController*)[self.storyboard instantiateViewControllerWithIdentifier:@"DueInVC"];
      UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    if ([dict[@"title"] isEqualToString:@"待收文件"]) {
        dueInVC.vcType = WaitForSignType;
        [self.navigationController pushViewController:dueInVC animated:YES];
    }else if ([dict[@"title"] isEqualToString:@"已收文件"]){
        dueInVC.vcType = AlreadySignType;
        [self.navigationController pushViewController:dueInVC animated:YES];
    }else if ([dict[@"title"] isEqualToString:@"已发文件"]){
        dueInVC.vcType = SenderSinType;
        [self.navigationController pushViewController:dueInVC animated:YES];
    }else if ([dict[@"title"] isEqualToString:@"待办文件"]){
        OAUpComingWorkController * upcomingWorkVC  = (OAUpComingWorkController*)[storyBoard instantiateViewControllerWithIdentifier:@"UpComingWorkVCID"];
        [self.navigationController pushViewController:upcomingWorkVC animated:YES];
    }else if ([dict[@"title"] isEqualToString:@"已办文件"]){
        OAToDoWorkViewController * todoWorkVC  = (OAToDoWorkViewController*)[storyBoard instantiateViewControllerWithIdentifier:@"TodoWorkVCID"];
        [self.navigationController pushViewController:todoWorkVC animated:YES];
    }else if ([dict[@"title"] isEqualToString:@"待阅文件"]){
        dueInVC.vcType = WaitForReadType;
        [self.navigationController pushViewController:dueInVC animated:YES];
    }else if ([dict[@"title"] isEqualToString:@"电子公告"]){
        OANoteViewController * noteVC  = (OANoteViewController*)[storyBoard instantiateViewControllerWithIdentifier:@"noteVCID"];
        [self.navigationController pushViewController:noteVC animated:YES];
    }else if ([dict[@"title"] isEqualToString:@"最新收文"]){
        OANewInViewController * newInVC  = (OANewInViewController*)[storyBoard instantiateViewControllerWithIdentifier:@"newInVCID"];
        [self.navigationController pushViewController:newInVC animated:YES];
    }else if ([dict[@"title"] isEqualToString:@"最新发文"]){
        OANewSendViewController * sendVC  = (OANewSendViewController*)[storyBoard instantiateViewControllerWithIdentifier:@"sendVCID"];
        [self.navigationController pushViewController:sendVC animated:YES];
    }else if ([dict[@"title"] isEqualToString:@"短信平台"]){
        OASMSViewController * smsVC = (OASMSViewController*)[self.storyboard instantiateViewControllerWithIdentifier:@"SMSVCID"];
        smsVC.vcType = SMSViewControllerType;
        [self.navigationController pushViewController:smsVC animated:YES];
    }else if ([dict[@"title"] isEqualToString:@"通讯录"]){
        OAAddressViewController * addressVC = (OAAddressViewController*)[self.storyboard instantiateViewControllerWithIdentifier:@"AddressVCID"];
        [self.navigationController pushViewController:addressVC animated:YES];
    }else if ([dict[@"title"] isEqualToString:@"邮件"]){
        OAHomeEmailViewController * homeEmailVC = (OAHomeEmailViewController*)[self.storyboard instantiateViewControllerWithIdentifier:@"HomeEmailID"];
        [self.navigationController pushViewController:homeEmailVC animated:YES];
    }else if ([dict[@"title"] isEqualToString:@"登记簿"]){
        dengjiTableViewController * homeEmailVC = [[dengjiTableViewController alloc]init];
        //(OAHomeEmailViewController*)[self.storyboard instantiateViewControllerWithIdentifier:@"HomeEmailID"];
        [self.navigationController pushViewController:homeEmailVC animated:YES];
    }
    
}

- (IBAction)logout:(id)sender {
//     [_helper logoutVpn];
//
//    OALoginViewController * loginVC =  [self.storyboard instantiateViewControllerWithIdentifier:@"LoginVC"];
//             loginVC.type = @"1";
//
//    self.view.window.rootViewController = loginVC;
    
ViewController3 *vc = [[ViewController3 alloc]init];
[self.navigationController pushViewController:vc animated:YES];
}

@end
